module.exports = (function () {
    var nameSpace = require('./../config.json').redisNamespace;
    var redis = require('redis');
    var User = require('./../models/User.js');

    var isExceptionsString = function (path) {
        path = path.toLowerCase();
        //定义了允许用户不经登录就可以访问页面的特例
        var allowed = ['login', 'register', 'findpassword'];
        var is = false;
        for (var i = 0; i < allowed.length; i++) {
            if (path.indexOf(allowed[i]) >= 0) {
                is = true;
                break;
            }
        }
        return is;
    };

    var process = function (req, res, next) {
        if (isExceptionsString(req.path)) {
            next();
        } else {
            var uid = req.cookies.uid || null;
            var username = req.cookies.username || "";
            var redisClient = redis.createClient();
            var redirectUrl = '/login?' + encodeURI(req.url.replace(/^\//, ''));
            if (uid) {
                redisClient.get(nameSpace + ':user:' + uid, (function (req, res, next) {
                    return function (err, reply) {
                        var user = JSON.parse(reply); //给user赋值
                        user.uid = uid;
                        if (err || !reply || JSON.parse(reply).userName.toLowerCase() !== username.toLowerCase()) {
                            res.redirect(redirectUrl);
                        } else {
                            var extend = require('extend');
                            req.user = extend(new User(), user); //将user传递给下面的中间件
                            next();
                        }
                        redisClient.quit();
                    };
                })(req, res, next));
            } else {
                console.log('cookies not vialid, redirect to login page!');
                res.redirect(redirectUrl);
            }
        }
    };
    return process;
})();
